/*
** 日志格式化器
*/

#pragma once

#include <string>
#include "abstract_loger.hpp"
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>

namespace lxz
{

    class log_fmter
    {
    public:
        static std::string work(log_level level, const char *file, const char *function, const int line, const char *fmt, ...)
        {
            std::string log;
            char buf[4096] = {0};
            time_t t = time(nullptr);
            struct tm p = {0};
            const char *key = nullptr;

            if (!localtime_r(&t, &p))
            {
                return log;
            }

            switch (level)
            {
            case LOG_LEVEL_DEBUG:
                key = "debug";
                break;
            case LOG_LEVEL_INFO:
                key = "info";
                break;
            case LOG_LEVEL_WARN:
                key = "warn";
                break;
            case LOG_LEVEL_ERR:
                key = "error";
                break;
            default:
                key = "*";
                break;
            }

            (void)snprintf(buf + strlen(buf), 4096 - strlen(buf), "<%s>[%d-%d-%d %d:%d:%d][%s:%s:%d]",
                           key,
                           p.tm_year + 1900, p.tm_mon + 1, p.tm_mday, p.tm_hour, p.tm_min, p.tm_sec,
                           file, function, line);

            va_list ap;
            va_start(ap, fmt);
            vsnprintf(buf + strlen(buf), 4096 - strlen(buf), fmt, ap);
            va_end(ap);

            log += buf;

            return log;
        }
    };

}